package com.weimin.springbootgrpcclient.controller;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
import com.weimin.proto.BaseMessage;
import com.weimin.springbootgrpcclient.service.IGrpcService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

import org.springframework.http.MediaType;


@Slf4j
@RestController
// 设置方法强制返回type为json使protobuf消息转换器生效
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
public class GrpcController {

    private final IGrpcService grpcService;

    @RequestMapping(value = "commonMethod")
    public BaseMessage.Message commonMethod(String msg) {
        return grpcService.commonMethod(msg);
    }

    @RequestMapping("serviceEndStreamMethod")
    public List<BaseMessage.Message> serviceEndStreamMethod(String msg) {
        return grpcService.serviceEndStreamMethod(msg);
    }

    @RequestMapping("clientStreamMethod")
    public BaseMessage.Message clientStreamMethod() throws InterruptedException {
        List<BaseMessage.Message> list = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            BaseMessage.MessageRequest request = BaseMessage.MessageRequest.newBuilder()
                    .setId(String.valueOf(System.currentTimeMillis()))
                    .setData("clientStreamMethod 请求数据 -> " + i).build();
            BaseMessage.Message message = BaseMessage.Message.newBuilder()
                    .setPackType(BaseMessage.Message.PackType.REQUEST)
                    .setRequest(request).build();
            list.add(message);
        }
        return grpcService.clientStreamMethod(list);
    }

    @RequestMapping("bidirectionalFlowMethod")
    public List<BaseMessage.Message> bidirectionalFlowMethod() throws InterruptedException {
        List<BaseMessage.Message> list = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            BaseMessage.MessageRequest request = BaseMessage.MessageRequest.newBuilder()
                    .setId(String.valueOf(System.currentTimeMillis()))
                    .setData("bidirectionalFlowMethod 请求数据 -> " + i).build();
            BaseMessage.Message message = BaseMessage.Message.newBuilder()
                    .setPackType(BaseMessage.Message.PackType.REQUEST)
                    .setRequest(request).build();
            list.add(message);
        }
        return grpcService.bidirectionalFlowMethod(list);
    }
}
